//
//  JkmBarCodeView.swift
//  SinaWb
//
//  Created by Jiang on 5/18/16.
//  Copyright © 2016 Jiang. All rights reserved.
//

import UIKit
import SnapKit
import AVFoundation
class JkmQrView: UIView,AVCaptureMetadataOutputObjectsDelegate{
    
//MARK: 改变容器视图的高度
    var backviewHeight :CGFloat?{
        didSet{
            ContainerView.snp_updateConstraints(closure: { (make) in
                make.height.equalTo(backviewHeight!)
            })
            startAnimation()
        }
    }
//MARK: -
//MARK:设置视图子视图和布局
    override init(frame: CGRect) {
        super.init(frame: frame)
        SetUI()
    }
    func SetUI(){
        
        addSubview(ContainerView)
        addSubview(MessageLable)
        ContainerView.addSubview(ScanimageView)
        ContainerView.addSubview(FrameimageView)
        
        ContainerView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY)
            make.width.equalTo(self.frame.width * 0.5)
            make.height.equalTo(self.frame.width * 0.5)
        }
        
        FrameimageView.snp_makeConstraints { (make) in
            make.edges.equalTo(superview ?? ContainerView).inset(UIEdgeInsetsMake(0, 0, 0, 0))
            
        }
        
        ScanimageView.snp_makeConstraints { (make) in
            make.bottom.equalTo(ContainerView.snp_top)
            make.centerX.equalTo(ContainerView.snp_centerX)
            make.width.equalTo(ContainerView.snp_width)
        }
        
        MessageLable.snp_makeConstraints { (make) in
            make.top.equalTo(ContainerView.snp_bottom).offset(10)
            make.centerX.equalTo(ContainerView.snp_centerX)
        }
        
        
        layoutIfNeeded()
        //不能在init中定义动画
    }
    
//MARK: -
//MARK: - 添加动画和设置相机捕捉
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置动画
        startAnimation()
        
        //设置相机捕捉
        setCamera()
        
        
    }
    
//MARK:扫描图片动画
    private func startAnimation(){
        
        //1.清楚之前的动画
        //2.恢复到容器视图的顶端，绘制
        //3.执行动画，绘制
        ScanimageView.layer.removeAllAnimations()
        
        ScanimageView.snp_updateConstraints(closure: { (make) in
            make.bottom.equalTo(self.ContainerView.snp_top)
        })
        
        layoutIfNeeded()
        
        UIView.animateWithDuration(1.5) {
            
            UIView.setAnimationRepeatCount(MAXFLOAT)
            
            self.ScanimageView.snp_updateConstraints(closure: { (make) in
                
                make.bottom.equalTo(self.ContainerView.snp_top).offset(self.ContainerView.frame.height + self.ScanimageView.frame.height)
            })
            
            self.layoutIfNeeded()
            
        }
    }

//MARK: 设置相机捕捉
    private  func setCamera(){
        
        /**
         *  初始化相机捕捉设备输入源
         *
         *  @param CameraDevice 相机设备
         *
         *  @return  用相机设备初始化后的输入源
         */
        CaptureDeviceIntput  = try?  AVCaptureDeviceInput(device: CameraDevice)
        
        // 判断输入源能否添加到捕捉任务中
        if !session.canAddInput(CaptureDeviceIntput) {
            return
        }
        // 判断输出源能否添加到捕捉任务中
        if !session.canAddOutput(CaptureOutput) {
            return
        }
        
        //添加两个源
        session.addInput(CaptureDeviceIntput)
        session.addOutput(CaptureOutput)
        
        //设置输出源的代理和队列
        CaptureOutput.setMetadataObjectsDelegate(self, queue:dispatch_get_main_queue())
        
        //设置源数据类型  当前使用的是:二维码类型
        CaptureOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
        
        //AVCaptureVideoPreviewLayer是CALayer的子类，可被用于自动显示相机产生的实时图像
        //使用session初始化一个相机预览图层
        cameraLayer = AVCaptureVideoPreviewLayer(session: session)
        
        //设置图层大小
        cameraLayer!.frame = frame
        
        //插入到视图的最底部
        layer.insertSublayer(cameraLayer!, atIndex: 0)
        

        //任务开始
        session.startRunning()
        QrCodeRect.lineWidth = 2
        QrCodeRect.fillColor = UIColor.clearColor().CGColor
        QrCodeRect.strokeColor = UIColor.greenColor().CGColor
        layer.addSublayer(QrCodeRect)
    }
    
    //扫描时的数据代理
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!){
        
        if metadataObjects.count == 0 {
            MessageLable.text = "没有发现二维码"
            QrCodeRect.path = nil
            return
        }
        
        if  let  message = metadataObjects.first as? AVMetadataMachineReadableCodeObject where message.type == AVMetadataObjectTypeQRCode && message.stringValue != nil{
            
            MessageLable.text = message.stringValue
            
            let qrcode = cameraLayer!.transformedMetadataObjectForMetadataObject(message) as? AVMetadataMachineReadableCodeObject
            
            if  let location :[[String:CGFloat]] = qrcode?.corners as? [[String:CGFloat]]{

                let path = UIBezierPath()
                var i = 0
                for item in location{
                    item.count
                    if i == 0{
                        path.moveToPoint(CGPoint(x: item["X"]!, y:item["Y"]!))
                    }
                    path.addLineToPoint(CGPoint(x: item["X"]!, y:item["Y"]!))
                    i += 1
                }
                path.closePath()
                
                QrCodeRect.path = path.CGPath
            
            }

            
            
        }
    }


//MARK: -
//MARK: -  相机属性
    
    /// 获取相机设备
    private  var CameraDevice : AVCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    /// 获取捕捉任务
    private   var session : AVCaptureSession = AVCaptureSession()
    /// 捕捉输入源
    private  var CaptureDeviceIntput : AVCaptureDeviceInput?
    /// 捕捉输出源
    lazy  private  var CaptureOutput: AVCaptureMetadataOutput = {
        
        let out = AVCaptureMetadataOutput()
        
        let viewframe = self.bounds
        let containerframe = self.ContainerView.frame
        let x = containerframe.origin.y / viewframe.height
        let y = containerframe.origin.x / viewframe.width
        let w = containerframe.height / viewframe.height
        let h = containerframe.width / viewframe.width

        out.rectOfInterest = CGRect(x : x, y: y, width: w, height: h)
        
        return out
    }()

    
//MARK: - 视图控件属性
    //容器视图
    lazy   var ContainerView : UIView = {
        let view = UIView()
        view.clipsToBounds = true
        view.backgroundColor = UIColor.clearColor()
        return view
        
    }()
    
    //扫描图片视图
    lazy   private var ScanimageView: UIImageView = {
        
        let imageView = UIImageView(image: UIImage(named: "qrcode_scanline_qrcode"))
        
        return imageView
        
    }()
    
    //边框图片视图
    lazy  private var FrameimageView : UIImageView = {
        
        let ImageView = UIImageView(image: UIImage(named: "qrcode_border"))
        
        return ImageView
        
    }()
    //相机展示图层
    private var cameraLayer : AVCaptureVideoPreviewLayer?
    //二维码边框
    private var QrCodeRect : CAShapeLayer = CAShapeLayer()
    //扫描信息栏
    lazy  var MessageLable : UILabel = {
       let lable = UILabel()
        lable.textColor = UIColor.lightGrayColor()
        lable.textAlignment = .Center
        lable.sizeToFit()
        return lable
        
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

}
